<template>
    <div>
        <page-header title="欢迎使用">
            <template #content>
                <div>
                    这是头部信息
                </div>
            </template>

        </page-header>
       <el-row :gutter="20" style="margin: 0 10px;">
            <el-col :lg="8">
                <page-main title="扫描地图" style="margin: 0 0 20px 0;">   
                <span>地图名称</span>
                  <el-select  v-model="dataManager.current.mapName" placeholder="请选择" @change="handleMapChange">
                    <el-option
                      v-for="map in dataManager.mapList"
                      :key="map.id"
                      :label="map.name"
                      :value="map.name">
                    </el-option>
                  </el-select>
                  <el-collapse v-model="activeCollapse" accordion>
                    <el-collapse-item title="地图定点列表" name="1">
                      <!-- radio 选择 -->
                      <el-radio-group  v-model="dataManager.current.positionName" @change="handlePositionChange">
                        <el-radio v-for="(positionName) in dataManager.positionNameList" :label="positionName" :key="positionName">{{ positionName }}</el-radio>
                      </el-radio-group>
                    </el-collapse-item>
                  </el-collapse>

                  <el-divider >新建扫描<i style="color: crimson;"></i></el-divider>
                  <el-button type="success" @click="createMap" :disabled="canvasManager.editStatus">新建扫描</el-button>
                  <el-button type="primary" @click="scanMapPng" :disabled="canvasManager.editStatus">查看扫描地图</el-button>
                  <el-button type="primary" @click="getScanPng" >获取实时扫描地图Png</el-button>

                <el-divider >定点设置</el-divider>
              
                  <el-button type="success" @click="addPosition" :disabled="canvasManager.editStatus">新增定点</el-button>
                  <el-button type="primary" @click="renamePosition" :disabled="canvasManager.editStatus">重命名</el-button>
                  <el-button type="danger" @click="removePosition" :disabled="canvasManager.editStatus">删除定点</el-button>

                
                <el-button-group v-if="canvasManager.editStatus">
                <el-divider >打点</el-divider>
                  <el-button v-if="!canvasManager.clickStatus" type="primary"  @click="recordPoint">打点</el-button>
                  <el-button v-if="canvasManager.clickStatus" type="success" @click="cancelRecordPoint">取消打点</el-button>
                  <el-button type="warning" @click="savePosition">保存</el-button>
                  <el-button type="danger" @click="cancel">取消</el-button>
                </el-button-group>
          
                  <el-divider >完成扫描<i style="color: crimson;"></i></el-divider>
                  <el-button type="primary" @click="stopScanMap" :disabled="canvasManager.editStatus">结束扫描并保存</el-button>
                  <el-button type="danger" @click="cancelScan" :disabled="canvasManager.editStatus">取消扫描</el-button>
                </page-main>
                
            </el-col>
            <el-col :lg="16">
               <page-main title="地图" style="margin: 0 0 20px 0;" @mousewheel.prevent>
                      <div class="question">
                        <canvas id="map" class="map"></canvas>
                      </div>
                </page-main>
            </el-col>
        </el-row>
    </div> 

</template>

<script>
import CanvasManager from '@/static/CanvasManagerPosition'
import DataManager from '@/static/DataManagerPosition';
import gsApi from "@/api/gsApi";

  export default {
    name: "ScanMap",
    metaInfo: {
      meta: [
        { charset: 'utf-8' },
        { name: 'description', content: '这是一个测试' }
      ]
    },
    data() {
      return {
        canvasManager:'',
        dataManager:new DataManager(),
        activeCollapse:'1',
        scanIntervalFlag:''
      }
    },
    created(){
    },
    mounted() {
      this.loadData();
    },
    methods:{
      async loadData(){
        await this.dataManager.loadMaps();
        await this.dataManager.location();
        await this.dataManager.loadPositions(this.dataManager.mapList[0].name);
       
        // 这里需要等待数据加载完后，再初始化canvasManager。因为需要知道第一张地图的名字，用作显示
        this.canvasManager=new CanvasManager({
          canvasId:'map',
          mapName:this.dataManager.mapList[0].name,
        })
      },
     handleMapChange(mapName){
        this.canvasManager.reloadImg(mapName);
        this.dataManager.loadPositions(mapName);
      },
      async getScanPng(){
        // this.canvasManager.clearMap();
        this.canvasManager.loadScanningImg();
      },
      handlePositionChange(positionName){
        // 1. 清除画布的圆和字
        this.canvasManager.clearObjectCircle();
        this.canvasManager.clearObjectText();
        // 2. 再绘制新的点
        this.canvasManager.drawPosition({positionName,dataManager:this.dataManager});
      },

       addPosition(){//添加定点
        // this.canvasManager.clearObject(); // 清理地图路径
        this.canvasManager.clearObjectCircle();
        this.canvasManager.clearObjectText();
        this.canvasManager.editStatus=true;
      },

      renamePosition(){//修改名称
        const mapName=this.dataManager.current.mapName
        const originPosition = this.dataManager.current.positionName;
        if(originPosition=== ''){
            this.$message.info('请选择定点')
            return
          }
        this.$prompt('请输入新名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async({ value }) => {
          try {
              const res = await gsApi.renamePosition(mapName,originPosition,value)
              if(res.data.msg==='successed'){
                this.$message.success('修改成功')
              }else{
                this.$message.error(res.data.msg);
              }
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
            }
          this.loadData();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });       
        });
      },

      /**
       * 删除定点数据
       */
     removePosition(){
          const positionName=this.dataManager.current.positionName;
          const mapName=this.dataManager.current.mapName;
          if(positionName=== ''){
            this.$message.info('请选择定点')
            return
          }
        this.$confirm('此操作将永久删除该点, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async() => {
              try{
                const res = await gsApi.deletePosition(mapName, positionName)
                console.log(res)
                if(res.data.msg==='successed'){
                  this.$message.success('定点' + positionName + '删除成功')
                  // 删除成功后，重新加载手绘路径
                  this.dataManager.loadPositions(mapName);
                  // 取消选中路径
                  this.dataManager.current.positionName = ''
                  // 清理canvas 轨迹
                  this.canvasManager.clearObject();
                }else{
                  this.$message.error("删除定点失败，详见控制台")
                }
              }catch (err) {
                console.log(err);
                this.$message.error('删除失败，详见控制台')
              }
            this.loadData();
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });     
         },

      async scanMap(value){//新建扫描
      try {
              const res = await gsApi.scanMap(value)
              if(res.data.msg==='successed'){
                this.$message.success('新建成功,等待7秒后开始扫描')
              }else{
                this.$message.error(res.data.msg);
              }
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
            }
      },
        createMap(){//新建扫描
          this.$prompt('请输入地图名称', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            //启动扫描模块
            this.scanMap(value);
            //启动地图实时刷新模块
            this.canvasManager.clearMap();
            setTimeout(() => {
              this.scanIntervalFlag = setInterval(() => {
                this.canvasManager.loadScanningImg();
              }, 500);
            }, 7000);

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        },

        async cancelScan(){//取消扫描
        try {
          const res = await gsApi.cancelScan()
          clearInterval(this.scanIntervalFlag);
          if(res.data.msg==='successed'){
            this.$message.success('扫描已取消')
          }else{
            this.$message.error(res.data.msg);
           }
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },

        async stopScanMap(){//结束扫描保存地图(异步)
        try {
          const res = await gsApi.stopScanMap()
          if(res.data.msg==='successed'){
            this.$message.success('扫描成功');
          }else{
            this.$message.error(res.data.msg);
           }
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },

       async scanMapPng(){// 获取实时扫地图图片png
        const mapName=this.dataManager.current.mapName
        this.canvasManager.reloadImg(mapName);
        this.canvasManager.loadScanMap(mapName);
    
       },

        /**
       * 切换打点状态
       */
      recordPoint(){
        this.canvasManager.clickStatus=true;
      },
      /**
       * 取消打点状态
       */
      cancelRecordPoint(){
        this.canvasManager.clickStatus=false;
      },
      /**
       * 保存定点数据
       */
       savePosition(){
        // 根据再canvas上 打的点，生成要提交的数据
        const positionBean=this.canvasManager.generatePosition();
        console.log(positionBean);
        if(positionBean.name==undefined){
          this.$message.error("请先在图片上打点")
          return 
        }

            //向机器人中发送保存定点的请求
            this.$prompt('请输入定点名称', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern:/^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
              inputErrorMessage: '只能输入英文/数字/汉字'
            }).then(async({ value }) => {
                positionBean.name = value;
                try{
                  const res=await gsApi.insertPosition(positionBean);
                  if(res.data.msg==='successed'){
                    this.$message.success("定点"+positionBean.name+'保存成功')
                    // 保存成功后，重新加载路径数据，并且选中新添加的路径
                    await this.dataManager.loadPositions(this.dataManager.current.mapName);
                    this.dataManager.current.positionName=positionBean.name;
                    this.canvasManager.editStatus=false;
                  }else{
                    this.$message.error("出现问题" + res.data.msg)
                  }
                }
                catch(err){
                  console.log(err)
                  this.$message.error("出现异常，详见控制台")
                }

            }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });       
        });

      },
      cancel(){
        // 清理canvas 暂存的打点数据
        // this.canvasManager.clearObject(); // 清理地图路径
        this.canvasManager.clearObjectCircle();
        this.canvasManager.clearObjectText();
        this.canvasManager.tempPoints=[];
        // 退出编辑状态
        this.canvasManager.clickStatus=false;
        this.canvasManager.editStatus=false;
        //清空tempPosition信息，以免点保存的时候误保存最后一次遗留的点
        this.canvasManager.tempPosition={};
        // 重新绘制选中的路径
        //this.handlePositionChange(this.dataManager.current.positionName);
      }
    }
  }
</script>